from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from app.api.deps import get_db
from app.core.config import settings
from app.core.security import create_access_token
from app.crud.user import get_user_by_openid, create_user, update_user
from app.schemas.user import UserCreate, User
from app.utils.wechat import get_openid

router = APIRouter(prefix="/auth", tags=["auth"])

@router.post("/wechat/login")
async def wechat_login(
    code: str,
    nickname: str = None,
    avatar: str = None,
    db: Session = Depends(get_db)
):
    """微信一键登录"""
    try:
        # 获取openid
        openid = get_openid(code)
        
        # 查找或创建用户
        user = get_user_by_openid(db, openid)
        if not user:
            user = create_user(db, UserCreate(
                openid=openid,
                nickname=nickname,
                avatar=avatar
            ))
        elif nickname or avatar:
            # 更新用户信息
            user = update_user(db, user.id, nickname, avatar)
            
        # 生成token
        access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
        access_token = create_access_token(
            data={"sub": str(user.id)},
            expires_delta=access_token_expires
        )
        
        return {
            "access_token": access_token,
            "token_type": "bearer",
            "user_info": user
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        ) 